
import UIKit

extension String {
    
    //是否为邮箱
    var isValidEmail: Bool {
        // http://emailregex.com/
        let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
        return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
    }
    
    //是否为手机号
    var isValidPhoneNumber: Bool {
        // 定义正则表达式
        let phoneRegex = "^1[3-9]\\d{9}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: self)
    }
    
    func validatePassword() -> Bool {
        if self.count == 0 {
            return false
        }
        guard self.count >= 6,self.count <= 14 else {
            return false
        }
        return true
    }
    
    // 颜色
    var toColor: UIColor {
        return UIColor.color(hexString: self, alpha: 1.0)
    }
    
    // 图片
    var toImage: UIImage? {
        UIImage(named: self)
    }
    
    var intValue: Int {
        return (self as NSString).integerValue
    }
    
    var isBlank : Bool {
        return allSatisfy({$0.isWhitespace})
    }
    
    var isNewLine: Bool {
        return allSatisfy({$0.isNewline})
    }
    
    var toYear: String {
        if self == "0001-01-01" {
            return ""
        }
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd"
        if let oldDate = format.date(from: self) {
            let currentDate = Date()
            let timeInterval = currentDate.timeIntervalSince(oldDate)
            let time = timeInterval/(3600*24*365)
            return "\(Int(time))"
        }
        return ""
    }
    
    /// add char at index
    mutating func addString(_ string: String, at index: Int) {
        guard count > index else {
            return
        }
        let ind = self.index(self.startIndex, offsetBy: index)
        insert(contentsOf: string, at: ind)
    }
    
    var int: Int? {
        return Int(self)
    }
}

//MARK: - function
extension String {
    
    //TODO: - 转数组
    func toInfos(_ separated: String) -> [Self] {
        self.components(separatedBy: separated)
    }
    
    func convertDictionary() -> NSDictionary? {
        let string = (self as NSString).trimmingCharacters(in: CharacterSet.controlCharacters)
        guard let jsonData: Data = string.data(using: .utf8) else { return nil }
        if let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
            return dict as? NSDictionary
        }
        return nil
    }
    
    /// 计算文本宽度
    /// - Parameters:
    ///   - size: 期望size
    ///   - font: 字体
    /// - Returns: 文本宽度
    func caculateWidth(_ size: CGSize!,_ font: UIFont) -> CGFloat {
        var rect: CGRect = .zero
        DispatchQueue.global().sync {
            rect = NSString(string: self).boundingRect(with: size, options: NSStringDrawingOptions(rawValue: NSStringDrawingOptions.usesLineFragmentOrigin.rawValue | NSStringDrawingOptions.usesFontLeading.rawValue | NSStringDrawingOptions.usesDeviceMetrics.rawValue | NSStringDrawingOptions.truncatesLastVisibleLine.rawValue), attributes: [NSAttributedString.Key.font: font], context: nil)
        }
        return rect.size.width
    }
    
    /// 计算文本高度
    /// - Parameters:
    ///   - size: 期望size
    ///   - font: 字体
    /// - Returns: 文本高度
    func caculateHeight(_ maxWidth: CGFloat!,_ font: UIFont) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions(rawValue: NSStringDrawingOptions.usesLineFragmentOrigin.rawValue | NSStringDrawingOptions.usesFontLeading.rawValue | NSStringDrawingOptions.usesDeviceMetrics.rawValue | NSStringDrawingOptions.truncatesLastVisibleLine.rawValue), attributes: [NSAttributedString.Key.font: font], context: nil)
        return rect.size.height
    }
    
    /// 时间字符串 09:30 转为 double 9.5
    func timeStringToDouble() -> Double? {
        // 创建日期格式化器
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        
        // 将时间字符串转换为日期对象
        guard let date = dateFormatter.date(from: self) else {
            return nil
        }
        
        // 获取日历实例
        let calendar = Calendar.current
        
        // 提取小时和分钟部分
        let components = calendar.dateComponents([.hour, .minute], from: date)
        guard let hour = components.hour, let minute = components.minute else {
            return nil
        }
        
        // 计算总小时数
        let totalHours = Double(hour) + Double(minute) / 60.0
        return totalHours
    }
}
